package com.newenergy.wisehome.common.helper;

import android.content.Context;
import android.media.MediaPlayer;

/**
 * Created by kyx on 2018/1/24.
 */

public class VoiceHelper {

    private static Context mContext;
    private static volatile VoiceHelper myVoiceManager;
    private MediaPlayer mPlayer;
    private VoicePlayCallBack voicePlayCallBack;


    private VoiceHelper(Context context) {
        this.mContext = context;
    }


    public static VoiceHelper getInstance(Context context){
        if(myVoiceManager == null){
            synchronized(VoiceHelper.class){
                if(myVoiceManager == null){
                    myVoiceManager = new VoiceHelper(context);
                }
            }
        }
        return myVoiceManager;
    }


    public void initMediaPlay(int source,VoicePlayCallBack callBack){
        mPlayer = MediaPlayer.create(mContext, source);
        mPlayer.start();
        mPlayer.setOnCompletionListener(mPlayCompetedListener);
        mPlayer.setOnErrorListener(mPlayErrorListener);
        setVoicePlayListener(callBack);
    }


    public void release() {
        if (mPlayer != null) {
            mPlayer.release();
        }
    }


    /**
     * 播放器结束监听
     */
    private MediaPlayer.OnCompletionListener mPlayCompetedListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
           /* mDeviceState = MEDIA_STATE_PLAY_STOP;
            mHandler.removeMessages(MSG_TIME_INTERVAL);
            mMediaPlayer.stop();
            mMediaPlayer.release();
            */
            mPlayer.release();
            if (voicePlayCallBack != null) {
                voicePlayCallBack.playFinish();
            }

        }
    };


    /**
     * 播放器结束监听
     */
    private MediaPlayer.OnErrorListener mPlayErrorListener = new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {

            if (voicePlayCallBack != null) {
                voicePlayCallBack.playError();
                return true;
            }
            return false;
        }

    };



    /**
     * 播放录音回调监听
     */
    public interface VoicePlayCallBack {

        /**
         * 音频长度
         * 指定的某个时间段，以秒为单位
         */
//        void voiceTotalLength(long time, String strTime);

        /**
         * 播放中
         * 指定的某个时间段，以秒为单位
         */
//        void playDoing(long time, String strTime);

        //播放暂停
//        void playPause();

        //播放开始
//        void playStart();

        //播放结束
        void playFinish();

        //播放失败
        void playError();
    }

    /**
     * 播放监听
     *
     * @param callBack
     */
    public void setVoicePlayListener(VoicePlayCallBack callBack) {
        voicePlayCallBack = callBack;
    }

}
